<?php

namespace app\service;

use think\facade\Db;

class DashBoardService
{

    /**
     * 店名脱敏
     */
    public function maskShopName($shopName)
    {
        if (empty($shopName)) {
            return $shopName;
        }

        $length = mb_strlen($shopName, 'UTF-8');

        if ($length <= 3) {
            return $shopName;
        }

        return mb_substr($shopName, 0, 2, 'UTF-8') .
            str_repeat('*', $length - 3) .
            mb_substr($shopName, -1, null, 'UTF-8');
    }

    /**
     * 用户名脱敏
     */
    public function maskUsername($username)
    {
        if (empty($username)) {
            return $username;
        }

        $length = mb_strlen($username, 'UTF-8');

        if ($length <= 2) {
            return $username;
        }

        return mb_substr($username, 0, 2, 'UTF-8') .
            str_repeat('*', $length - 2) .
            mb_substr($username, -1, null, 'UTF-8');
    }


    // 获取大屏数据
    public function getDashboardStatistical($param)
    {
        $timeForm = $param['time_form'] ?? 'today';
        $regionId = $param['region_id'] ?? 1;

        // 基础查询（流水表）
        $baseQuery = Db::table('shop_earnings')
            ->alias('se')
            ->leftJoin('shop_main sm', 'se.shop_id = sm.id')
            ->leftJoin('coach_main cm', 'se.coach_id = cm.id')
            ->leftJoin('shop_region sr', 'se.region_id = sr.id')
            ->leftJoin('user u', 'se.user_id = u.id')
            ->where('se.region_id', $regionId)
            ->where('se.deletetime', null)
            ->whereNotIn('se.is_form', [7, 8]);

        // 时间范围
        switch ($timeForm) {
            case 'today':
                $baseQuery->whereDay('se.finance_time');
                break;
            case 'yesterday':
                $baseQuery->whereDay('se.finance_time', 'yesterday');
                break;
            case 'month':
                $baseQuery->whereMonth('se.finance_time');
                break;
            case 'last_month':
                $baseQuery->whereMonth('se.finance_time', 'last month');
                break;
            case 'year':
                $baseQuery->whereYear('se.finance_time');
                break;
        }

        // 门店收益（来源金额）
        $totalRevenue = (clone $baseQuery)->sum('cost');

        // 订单数
        $totalOrders = (clone $baseQuery)->count();

        // 客单价
        $averageOrderValue = $totalOrders > 0 ? $totalRevenue / $totalOrders : 0;

        // 业务类型分布 (会员卡·课程)
        $businessTypeData = $this->formatDistributionData(
            (clone $baseQuery)
                ->field([
                    'finance_form',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('finance_form')
                ->select(),
            ['card', 'course'],
            'finance_form'
        );

        // 卡类型收益分布（月卡·年卡）
        $cardTypeData = $this->formatDistributionData(
            (clone $baseQuery)
                ->where('finance_form', 'card')
                ->field([
                    'duration_form',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('duration_form')
                ->select(),
            ['exp', 'week', 'month', 'season', 'half', 'year', 'rest'],
            'duration_form'
        );

        // 课程类型收益分布（课程类型:exp=体验课,new=新人专享课,pt=私教课,bag=包课(时间限制)）
        $courseTypeData = $this->formatDistributionData(
            (clone $baseQuery)
                ->where('finance_form', 'course')
                ->field([
                    'course_form',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('course_form')
                ->select(),
            ['exp', 'new', 'pt', 'bag'],
            'course_form'
        );

        // 支付方式分布
        $paymentMethodData = $this->formatDistributionData(
            (clone $baseQuery)
                ->field([
                    'pay_form',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('pay_form')
                ->select(),
            [0, 1, 2, 3, 4, 5],
            'pay_form'
        );

        // 订单来源分析
        $orderSourceData = $this->formatDistributionData(
            (clone $baseQuery)
                ->field([
                    'is_form',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('is_form')
                ->select(),
            [0, 1, 2],
            'is_form'
        );

        // 门店排名
        $shopRanking = (clone $baseQuery)
            ->field([
                'se.shop_id',
                'sm.name as shop_name',
                'SUM(cost) as total_revenue',
                'COUNT(*) as order_count'
            ])
            ->group('se.shop_id, sm.name')
            ->order('total_revenue DESC')
            ->limit(10)
            ->select();

        // 教练业绩排行
        $coachRanking = (clone $baseQuery)
            ->where('se.coach_id', '>', 0)
            ->field([
                'se.coach_id',
                'cm.name',
                'SUM(cost) as total_revenue',
                'COUNT(*) as order_count'
            ])
            ->group('se.coach_id')
            ->order('total_revenue DESC')
            ->limit(10)
            ->select();

        // 退款数据
        $refundData = $this->formatDistributionData(
            (clone $baseQuery)
                ->field([
                    'is_refund',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('is_refund')
                ->select(),
            [0, 1],
            'is_refund'
        );

        // 总支付手续费(0.56%)
        $totalCommission = (clone $baseQuery)->sum('commission');

        // 总平台服务费用
        $totalServiceFee = (clone $baseQuery)->sum('serve');

        // 结算状态
        $settlementData = $this->formatDistributionData(
            (clone $baseQuery)
                ->field([
                    'is_sett',
                    'SUM(cost) as total_amount',
                    'COUNT(*) as order_count'
                ])
                ->group('is_sett')
                ->select(),
            [0, 1],
            'is_sett'
        );

        // 按小时统计今日数据
        $hourlyTrend = [];
        if ($timeForm === 'today') {
            $hourlyQuery = Db::table('shop_earnings')
                ->alias('se')
                ->where('se.region_id', $regionId)
                ->where('se.deletetime', null)
                ->whereDay('se.finance_time')
                ->field([
                    "HOUR(se.finance_time) as hour",
                    'SUM(cost) as hourly_revenue',
                    'COUNT(*) as hourly_orders'
                ])
                ->group('HOUR(se.finance_time)')
                ->order('hour ASC')
                ->select();

            for ($i = 0; $i < 24; $i++) {
                $hourData = [
                    'hour' => $i,
                    'hourly_revenue' => 0,
                    'hourly_orders' => 0
                ];
                foreach ($hourlyQuery as $item) {
                    if ($item['hour'] == $i) {
                        $hourData = $item;
                        break;
                    }
                }
                $hourlyTrend[] = $hourData;
            }
        }

        // 最近的100条订单
        $latestOrders = (clone $baseQuery)
            ->field([
                'se.id',
                'sm.name as shop_name',
                'sr.region_name as region_name',
                'se.cost as total_amount',
                'u.username',
                'se.finance_form',
                'se.pay_form',
                'se.finance_time'
            ])
            ->order('se.finance_time DESC')
            ->limit(50)
            ->select()
            ->toArray();

        // 使用
        foreach ($latestOrders as &$order) {
            $order['shop_name'] = $this->maskShopName($order['shop_name']);
            $order['username'] = $this->maskUsername($order['username']);
        }

        return [

            // 核心营收指标
            'total_revenue' => $totalRevenue,
            'total_orders' => $totalOrders,
            'average_order_value' => $averageOrderValue,

            // 业务构成分析
            'business_type_distribution' => $businessTypeData,
            'card_type_distribution' => $cardTypeData,
            'course_type_distribution' => $courseTypeData,

            // 渠道与支付分析
            'payment_method_distribution' => $paymentMethodData,
            'order_source_distribution' => $orderSourceData,

            // 地域与门店表现
            'shop_ranking' => $shopRanking,
            'coach_ranking' => $coachRanking,

            // 财务健康指标
            'refund_data' => $refundData,
            'total_commission' => $totalCommission,
            'total_service_fee' => $totalServiceFee,
            'settlement_data' => $settlementData,

            // 实时动态
            'hourly_trend' => $hourlyTrend,

            // 更新时间
            'update_time' => date('Y-m-d H:i:s'),
            // 最新100条订单
            'latest_orders' => $latestOrders,
        ];
    }

    /**
     * 格式化分布数据，确保所有分类都有默认值
     *
     * @param array $actualData 实际查询数据
     * @param array $allCategories 所有可能的分类
     * @param string $categoryField 分类字段名
     * @return array
     */
    private function formatDistributionData($actualData, $allCategories, $categoryField)
    {
        $result = [];

        // 创建默认值数组
        $defaultData = [];
        foreach ($allCategories as $category) {
            $defaultData[$category] = [
                $categoryField => $category,
                'total_amount' => 0,
                'order_count' => 0
            ];
        }

        // 合并实际数据
        foreach ($actualData as $item) {
            $categoryValue = $item[$categoryField];
            $defaultData[$categoryValue] = $item;
        }

        // 转换为索引数组
        return array_values($defaultData);
    }

    public function DashboardStatistical($param)
    {
        // 当天数据
        $currentData = $this->getDashboardStatistical($param);

        // 对比期数据（昨日或上月）
        $timeForm = $param['time_form'] ?? 'today';

        $compareParam = $param;

        switch ($timeForm) {
            case 'today':
                $compareParam['time_form'] = 'yesterday';
                break;
            case 'month':
                $compareParam['time_form'] = 'last_month';
                break;
            case 'year':
                $compareParam['time_form'] = 'last_year';
                break;
            default:
                $compareParam['time_form'] = 'yesterday';
        }

        $compareData = $this->getDashboardStatistical($compareParam);

        // 计算同比增长率
        $growthRate = [
            'revenue_growth' => 0,
            'order_growth' => 0
        ];
        // 计算营收同比增长率
        if ($compareData['total_revenue'] > 0) {
            // 累计营收同比增长率 = (今日（当月）累计营收额 - 昨日（上月）累计营收额) / 昨日（上月）累计营收额 * 100
            $growthRate['revenue_growth'] = (($currentData['total_revenue'] - $compareData['total_revenue']) / $compareData['total_revenue']) * 100;
        }
        // 计算订单量同比增长率
        if ($compareData['total_orders'] > 0) {
            // 累计订单同比增长率 = (今日（昨日）累计订单数 - 昨日（上图额）累计订单数) / 昨日（上月）累计订单数 * 100
            $growthRate['order_growth'] = (($currentData['total_orders'] - $compareData['total_orders']) / $compareData['total_orders']) * 100;
        }
        // 区域名称
        $region_name = Db::table('shop_region')->where('id', $param['region_id'])->value('region_name');

        return [
            'region' => $region_name,
            'current_data' => $currentData,
//            'compare_data' => $compareData,
            'growth_rate' => $growthRate,
            'update_time' => date('Y-m-d H:i:s')
        ];
    }

}